#include "Socket.h"
#include "log.h"
#include "InetAddress.h"


#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <strings.h>
#include<netinet/tcp.h>

// #include "Socket.h"
// #include "log.h"
// #include "InetAddress.h"

// #include <unistd.h>
// #include <sys/types.h>         
// #include <sys/socket.h>
// #include <strings.h>
// #include <netinet/tcp.h>
// #include <sys/socket.h>
Socket::~Socket()
{
    close(sockfd_);
}
void Socket::bindAddress(const InetAddress &localaddr)
{
    if (0 != bind(sockfd_, (sockaddr *)localaddr.getSockAddr(), sizeof(sockaddr_in)))
    {
        LOG_FATAL("bind sockfd:%d fail\n", sockfd_);
    }
};
void Socket::listen()
{
    if (0 != ::listen(sockfd_, 1024))
    {
        LOG_FATAL("listen sockfd:%d fail\n", sockfd_);
    }
};
int Socket::accept(InetAddress *peeraddr)//这里通过返回值返回连接套接字通过输出型参数返回客户端地址
{
    sockaddr_in addr;
    socklen_t len = sizeof(addr);
    bzero(&addr, sizeof(addr));
    int connfd = ::accept4(sockfd_, (sockaddr *)&addr, &len,SOCK_NONBLOCK | SOCK_CLOEXEC);
    if (connfd > 0)
    {
        peeraddr->setSockAddr(addr);
    }
    return connfd;
};
void Socket::shutdownWrite()
{
    if (::shutdown(sockfd_, SHUT_WR) < 0)
    {
        LOG_ERROR("Socket::shutdownWrite");
    }
};
void Socket::setKeepAlive(bool on)
{
    int optval = on ? 1 : 0;
    ::setsockopt(sockfd_, SOL_SOCKET, SO_KEEPALIVE, &optval, sizeof(optval));
};
void Socket::setReuseAddr(bool on)
{
    int optval = on ? 1 : 0;
    ::setsockopt(sockfd_, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof(optval));
};
void Socket::serReusePort(bool on)
{
    int optval = on ? 1 : 0;
    ::setsockopt(sockfd_, SOL_SOCKET, SO_REUSEPORT, &optval, sizeof(optval));
};
void Socket::setTcpNoDelay(bool on)
{
    int optval = on ? 1 : 0;
    ::setsockopt(sockfd_, IPPROTO_TCP,  TCP_NODELAY, &optval, sizeof(optval));
};